/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dto_pakinfo;

import collection.*;
import dao.UserDAO;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author Thinh
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "users")
public class Users {

    @XmlElement(required = true, name = "user")
    private List<User> users;
    @XmlTransient
    private boolean found;

    public Users() {
        found = false;
        users = new ArrayList<User>();
    }

    public Users(List<User> userList) {
        users = userList;
    }

    /**
     * @return the users
     */
    public List<User> getUsers() {
        if (users == null) {
            users = new ArrayList<User>();
        }
        return users;
    }

    public User getUserById(int id) {
        User result = null;
        boolean notFound = true;
        for (int i = 0; notFound && i < users.size(); i++) {
            if (users.get(i).getId() == id) {
                result = users.get(i);
                notFound = false;
            }
        }
        return result;
    }

    /**
     * @param users the users to set
     */
    public void setUsers(List<User> users) {
        this.users = users;
    }

    public void deleteUserNode(Node node, String id) {

        if (node == null || found) {
            return;
        }

        if (node.getNodeName().equals("user")) {
            //get attribute id
            String attributeId = node.getAttributes().getNamedItem("id").getNodeValue();
            if (id.equals(attributeId)) {
                //Update status
                NodeList childs = node.getChildNodes();
                Node temp;
                for (int i = 0; i < childs.getLength(); i++) {
                    temp = childs.item(i);
                    if (temp.getNodeName().equals("isDeleted")) {
                        if (temp.getTextContent().equals("true")) {
                            temp.setTextContent("false");
                        } else if (temp.getTextContent().equals("false")) {
                            temp.setTextContent("true");
                        }
                        found = true;
                        return;
                    }
                }
            }
        }

        int i = 0;
        NodeList childrenNodes = node.getChildNodes();
        while (i < childrenNodes.getLength()) {
            deleteUserNode(childrenNodes.item(i++), id);
        }
    }

    public void getUserIsNotAdmin(String filePath) throws FileNotFoundException, XMLStreamException {
        System.out.println("[DEBUG]Start DEBUG: ");
        Reader fileReader = null;

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        fileReader = new FileReader(new File(filePath));
        XMLEventReader reader = xmlInputFactory.createXMLEventReader(fileReader);
        User tempUser = null;
        Profile tempProfile = null;
        System.out.println("[DEBUG]Start DEBUG: ");

        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
                StartElement startElement = event.asStartElement();
                System.out.println(startElement.getName().getLocalPart());
                if ("user".equals(startElement.getName().getLocalPart())) {
                    found = false;
                    System.out.println("[DEBUG]User Node");
                    tempUser = new User();
                    Attribute attributeId = startElement.getAttributeByName(new QName("id"));
                    if (attributeId != null) {
                        tempUser.setId(Integer.parseInt(attributeId.getValue()));
                        System.out.println("[DEBUG]GET ID: " + tempUser.getId());
                    }
                } //end if user node
                else if ("username".equals(startElement.getName().getLocalPart())) {
                    System.out.println("Start [username]");
                    event = reader.nextEvent();
                    tempUser.setUsername(event.asCharacters().getData());
                    System.out.println("[Username]: " + tempUser.getUsername());
                } //end if username
                else if ("isAdmin".equals(startElement.getName().getLocalPart())) {
                    event = reader.nextEvent();
                    boolean isAdmin = Boolean.parseBoolean(event.asCharacters().getData());
                    if (isAdmin) {
                        found = true;
                    } else {
                        tempUser.setIsAdmin(Boolean.parseBoolean(event.asCharacters().getData()));
                    }
                } //end if isAdmin
                else if ("isDeleted".equals(startElement.getName().getLocalPart())) {
                    System.out.println("Start [isDeleted]");
                    if (!found) {
                        event = reader.nextEvent();
                        boolean isDeleted = Boolean.parseBoolean(event.asCharacters().getData());
                        tempUser.setIsDeleted(isDeleted);
                        System.out.println("[IsDeleted] " + tempUser.isIsDeleted());
                    }
                } //end isDeleted
                else if ("ProfileId".equals(startElement.getName().getLocalPart())) {
                    System.out.println("Start [ProfileId] " + found);
                    if (!found) {
                        event = reader.nextEvent();
                        tempProfile = new Profile();
                        tempProfile.setId(Integer.parseInt(event.asCharacters().getData()));
                        System.out.println("[ProfileId] " + tempProfile.getId());
                    }
                    //System.out.println("Khong tim thay roi");
                } //end ProfileId
                else if ("firstname".equals(startElement.getName().getLocalPart())) {
                    System.out.println("Start [firstname] " + found);
                    if (!found) {
                        event = reader.nextEvent();
                        tempProfile.setFirstname(event.asCharacters().getData());
                        System.out.println("[firstname]: " + tempProfile.getFirstname());
                    }
                } //end first name
                else if ("lastname".equals(startElement.getName().getLocalPart())) {
                    if (!found) {
                        event = reader.nextEvent();
                        tempProfile.setLastname(event.asCharacters().getData());
                        System.out.println("[lastname]: " + tempProfile.getLastname());
                    }
                } //end last name
                else if ("email".equals(startElement.getName().getLocalPart())) {
                    if (!found) {
                        event = reader.nextEvent();
                        tempProfile.setEmail(event.asCharacters().getData());
                        System.out.println("[email]: " + tempProfile.getEmail());
                    }
                } //end email
                else if ("address".equals(startElement.getName().getLocalPart())) {
                    if (!found) {
                        event = reader.nextEvent();
                        tempProfile.setAddress(event.asCharacters().getData());
                        System.out.println("[address]: " + tempProfile.getAddress());
                    }
                } //end address
                else if ("phoneNumber".equals(startElement.getName().getLocalPart())) {
                    if (!found) {
                        event = reader.nextEvent();
                        tempProfile.setPhoneNumber(event.asCharacters().getData());
                        System.out.println("[phoneNumber]: " + tempProfile.getAddress());
                    }
                }

            } //start element
            else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
                System.out.println("[Start End_ELEMENT] " + found);
                EndElement endElement = event.asEndElement();
                System.out.println(endElement.getName().getLocalPart());
                if (!found) {
                    if ("user".equals(endElement.getName().getLocalPart())) {
                        System.out.println("User ne cmm");
                        if (tempProfile == null) {
                            System.out.println("Profile null cmnr");
                        }
                        tempUser.setProfile(tempProfile);
                        if (tempUser == null) {
                            System.out.println("Null cmnr");
                        }
                        users.add(tempUser);
                        System.out.println("[DEBUG]Added: " + users.size());
                    }
                }
            }
        }
    }

    public void addUserNode(Document doc, User user) {
//        String imageNS = "http://xml.netbeans.org/schema/image";
        String prefixProfile = "ns2:";

        Element userElement = doc.createElement("user");
        userElement.setAttribute("id", user.getId() + "");

        Element usernameElement = doc.createElement("username");
        usernameElement.setTextContent(user.getUsername());
        //Append nameElement to productElement
        userElement.appendChild(usernameElement);

        Element isAdminElement = doc.createElement("isAdmin");
        isAdminElement.setTextContent(user.isIsAdmin() + "");
        userElement.appendChild(isAdminElement);

        Element createDateElement = doc.createElement("createDate");
        createDateElement.setTextContent(user.getCreateDate() + "");
        //Append descriptionElement to productElement
        userElement.appendChild(createDateElement);

        Element updateDateElement = doc.createElement("updateDate");
        createDateElement.setTextContent(user.getUpdateDate() + "");
        //Append descriptionElement to productElement
        userElement.appendChild(updateDateElement);


        Element isDeletedElement = doc.createElement("isDeleted");
        isDeletedElement.setTextContent(user.isIsDeleted() + "");
        userElement.appendChild(isDeletedElement);

       
        Element profileElement = doc.createElement("profile");

        Element ProfileId = doc.createElement(prefixProfile+"ProfileId");
        ProfileId.setTextContent(user.getProfile().getId()+"");
        profileElement.appendChild(ProfileId);

        Element firstname = doc.createElement(prefixProfile+"firstname");
        firstname.setTextContent(user.getProfile().getFirstname()+"");
        profileElement.appendChild(firstname);

        Element lastname = doc.createElement(prefixProfile+"lastname");
        lastname.setTextContent(user.getProfile().getLastname()+"");
        profileElement.appendChild(lastname);


        Element email = doc.createElement(prefixProfile+"email");
        email.setTextContent(user.getProfile().getEmail()+"");
        profileElement.appendChild(email);

        Element address = doc.createElement(prefixProfile+"address");
        address.setTextContent(user.getProfile().getAddress());
        profileElement.appendChild(address);
        
        Element phoneNumber = doc.createElement(prefixProfile+"phoneNumber");
        phoneNumber.setTextContent(user.getProfile().getPhoneNumber());
        profileElement.appendChild(phoneNumber);

        userElement.appendChild(profileElement);

        NodeList users = doc.getElementsByTagName("users");
        users.item(0).appendChild(userElement);
        
    }

    public boolean isFound() {
        return found;


    }

    /**
     * @param found the found to set
     */
    public void setFound(boolean found) {
        this.found = found;

    }

    public String transformUsersToXMLString() {
        StringBuilder sb = new StringBuilder();
        if (!users.isEmpty()) {
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<users>");
            for (User user : users) {
                sb.append("<user>");
            }
            sb.append("</users>");
        }
        return sb.toString();
    }
}
